<template>
  <div>

    <el-form :ref="granter" :model="user" :rules="role">

      <el-form-item
          prop="username"
          class="deep-input"
          v-if="granter===granters[0]"

      >
        <el-input placeholder="请输入用户名" type="text" prefix-icon="el-icon-user" v-model="user.username"/>
      </el-form-item>

      <el-form-item
          prop="password"
          class="deep-input"
          v-if="granter===granters[0]"

      >
        <el-input placeholder="请输入密码" type="password" prefix-icon="el-icon-lock" v-model="user.password"
                  show-password/>
      </el-form-item>

      <el-form-item
          prop="phone"
          class="deep-input"
          v-if="granter===granters[1]"

      >
        <el-input placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone" v-model="user.phone"/>
      </el-form-item>

      <el-row v-if="granter===granters[0]">
        <el-col :span="16">
          <el-form-item
              prop="captcha"
              class="deep-input"

          >
            <el-input placeholder="请输入验证码" type="text" prefix-icon="el-icon-edit" v-model="user.captcha"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-image @click="getCaptcha" class="captcha" :src="captcha.value"></el-image>
        </el-col>
      </el-row>

      <el-row v-if="granter===granters[1]">
        <el-col :span="15">
          <el-form-item
              prop="code"
              class="deep-input"

          >
            <el-input placeholder="请输入验证码" prefix-icon="el-icon-key" v-model="user.code"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="deep-send-btn">
          <el-button class="send-btn" @click="sendSms()" type="text">发送验证码</el-button>
        </el-col>
      </el-row>

      <el-form-item class="deep-btn">
        <el-button style="width: 100%;" @click="login(granter)">立即登录</el-button>
      </el-form-item>

    </el-form>


  </div>
</template>

<script>
import {post, get} from "@/utils/api";
import request from '@/utils/request';
import md5 from 'js-md5';

export default {

  data() {
    let checkPhone = (rule, value, callback) => { //自定义手机号码正则验证规则
      let check = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (!check.test(value)) {

        return callback(new Error('手机号码不合法(仅支持电信、移动、联通)~'));
      }
      //校验通过页必须 callback();
      return callback();

    }
    return {
      granters: ['captcha', 'sms'],
      user: {
        username: '',
        password: '',
        captcha: '',
        phone: '',
        code: ''
      },
      role: {
        username: [
          {required: true, message: "用户名不能为空~", trigger: 'blur'}
        ],
        password: [
          {required: true, message: "密码不能为空~", trigger: 'blur'}
        ],
        captcha: [
          {required: true, message: "验证码不能为空~", trigger: 'blur'}
        ],
        phone: [
          {required: true, message: "手机号码不能为空~", trigger: 'blur'},
          {validator: checkPhone, trigger: 'blur'}
        ],
        code: [
          {required: true, message: "验证码不能为空~", trigger: 'blur'}
        ]

      },
      captcha: {
        key: '',
        value: ''
      }

    }
  },
  props: ['granter'],
  methods: {
    login(ref) {

      //表单校验
      this.$refs[ref].validate((valid) => {
        console.log("校验内容:", valid);
        if (valid) {
          request({
            url: '/base-auth/oauth/token',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Captcha-key': this.captcha.key,
              'Captcha-code': this.user.captcha
            },
            method: 'POST',
            params: {
              client_id: 'client_sns',
              client_secret: 'secret_sns',
              grant_type: 'captcha',
              username: this.user.username,
              password: md5(this.user.password)
            }
          }).then(result => {

            if (result.status) {

              let token = `${result.data.token_type} ${result.data.access_token}`;

              let refreshToken = result.data.refresh_token;

              localStorage.setItem('token', token);
              localStorage.setItem('refreshToken', refreshToken);
              this.$message.success('登录成功~');
              this.$router.push('/home');
            } else {
              this.$message.error(result.response.data.error_description);
              //刷新验证码
              this.getCaptcha();
            }
          })

        }

      });


    },
    sendSms() {
      console.log('发送了短信验证码')

    },
    getCaptcha() {
      const promise = get({
        url: '/base-auth/oauth/captcha',
      }, false);

      promise.then(res => {
        if (res.code === 200) {
          this.captcha.key = res.data.key
          this.captcha.value = res.data.image;
        }
      });

    }
  },
  created() {
    console.log('我被触发了');
    this.getCaptcha();
  },
  watch: {
    //监听granter的变化，从而清除表单验证的结果
    granter: {
      handler(newValue, oldValue) {

        if (newValue !== oldValue) {
          this.$refs[oldValue].resetFields();

        }
      }
    }


  }

}
</script>

<style scoped>

.deep-input >>> input {
  border: 0;
  border-block-end: 1px solid #dcdfe6;
  border-radius: 0;
}

.deep-btn >>> button {
  border-radius: 0;
}

.deep-btn {
  margin-top: 30px;
  margin-bottom: 10px;
}

.captcha {
  width: 100%;
  /* width: 80px; */
  height: 40px;

}

.captcha:hover {
  cursor: pointer;
}

.send-btn {
  text-align: center;
  margin-left: 5px;
  width: 100%;
  color: #000;

}

.deep-send-btn >>> button {
  color: #999;
  border-left: 1px solid #dcdfe6;
}

</style>